import React, { useEffect, useRef, useState } from 'react';
import AvatarName from '@/pages/filePan/AvatarName';
import { Breadcrumb, Checkbox, Flex } from 'antd';
import FileRowItem from '@/pages/filePan/FileRowItem';

const FileListTable = () => {
  const fileRowItemRef = useRef();
  const avatarNameRef = useRef();
  const [checkAll, setCheckAll] = useState(false);
  // 面包屑列表
  const [breadList, setBreadList] = useState([
    {
      title: '根目录',
      filePid: '0',
    },
  ]);

  const updateTable = () => {
    fileRowItemRef.current.getTable();
  };

  // 点击某个面包屑触发
  const clickBread = (breadInfo) => {
    // 截取到当前点击的面包屑
    let currIndex = breadList.findIndex((item) => item.filePid === breadInfo.filePid);
    // 删除右侧面包屑
    setBreadList(breadList.slice(0, currIndex + 1));
  };

  const getCurrBread = () => {
    return breadList[breadList.length - 1];
  };

  const pushBread = (item) => {
    setBreadList([
      ...breadList,
      {
        title: item.fileName,
        filePid: item.fileId,
      },
    ]);
  };

  const updateFileNumber = () => {
    avatarNameRef.current.getUserFileSize();
  };

  const changeCheckAll = (check) => {
    setCheckAll(check);
    if (check) {
      fileRowItemRef.current.checkAll(true);
    } else {
      fileRowItemRef.current.checkAll(false);
    }
  };

  const switchCheckAll = (check) => {
    setCheckAll(check);
  };

  // 监听 breadList 的变化，一旦变化，更新表格
  useEffect(() => {
    updateTable();
    setCheckAll(false);
    fileRowItemRef.current.checkAll(false);
  }, [breadList]);

  return (
    <div className={'file-content'}>
      <AvatarName
        ref={avatarNameRef}
        updateTable={updateTable}
        getCurrBread={getCurrBread}
        updateFileNumber={updateFileNumber}
      />

      {/*面包屑*/}
      <Breadcrumb
        className={'breadcrumb'}
        separator=">"
        items={breadList.map((item) => ({
          ...item,
          onClick: () => clickBread(item),
        }))}
      />

      <div className={'file-table'}>
        <div className={'item-content item-title'}>
          <Flex gap={10} align={'center'} style={{ flex: 1 }}>
            <Checkbox checked={checkAll} onChange={(e) => changeCheckAll(e.target.checked)} />
            <div>名称</div>
          </Flex>

          <div style={{ width: '200px' }}>最后修改时间</div>
          <div style={{ width: '150px' }}>大小</div>
        </div>

        <FileRowItem
          ref={fileRowItemRef}
          getCurrBread={getCurrBread}
          pushBread={pushBread}
          updateFileNumber={updateFileNumber}
          switchCheckAll={switchCheckAll}
        />
      </div>
    </div>
  );
};

export default FileListTable;
